﻿using CaseManagerLibrary.Auth;
using CaseManagerLibrary.Log;
using CaseManagerLibrary.Models;
using PSDClientService.Burn;
using PSDClientService.Download;
using PSDClientService.SystemSettings;
using PSDLib;
using PSDLib.Models;
using PSDLib.Protocols;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Net.Mime.MediaTypeNames;

namespace PSDClientService
{
    public class ClientServiceContext
    {
        public ILog Logger { get; set; }

        public string UserName { get; set; }
        public string Password { get; set; }
        public bool RunAsService { get; set; }
        public string LogType { get; set; }

        public bool Running { get; set; }
        public string UUID { get; set; }
        public dl_download_device Device { get; set; }

        public DeviceManager DeviceManager { get; set; }
        public MessageManager MessageManager { get; set; }
        public HeartbeatManager HeartbeatManager { get; set; }

        public DownloadContext DownloadContext { get; set; }

        public BurnContext BurnContext { get; set; }

        public ClientServiceContext()
        {
            UUID = DeviceUUID.GetUUID();
            DeviceManager = new DeviceManager(this);
            MessageManager = new MessageManager(this);
            HeartbeatManager = new HeartbeatManager(this);
            DownloadContext = new DownloadContext(this);
            BurnContext = new BurnContext(this);
        }

        /// <summary>
        /// 初始化服务上下文
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="logtype"></param>
        /// <param name="runAsService"></param>
        /// <returns></returns>
        public HResult Init(string password, string logtype, bool runAsService)
        {
            UserName = UUID;
            Password = password;
            LogType = logtype;
            RunAsService = runAsService;

            HResult result = null;

            if (AppSettings.Setting.Read())
            {
                switch (logtype)
                {
                    case "text":
                        Logger = new TextLog(AppSettings.Setting.LogPath);
                        break;
                    case "sql":
                        Logger = new SQLiteLog(AppSettings.Setting.LogPath, AppSettings.Setting.DeviceVersion, UUID);
                        break;
                    default:
                        Logger = new ConsoleLog();
                        break;
                }


                //登录验证
                //result = LoginService.Login(AppSettings.Setting.ApiServerAddress, UserName, Password);
                if (String.IsNullOrEmpty(AppSettings.Setting.PemFile))
                {
                    result = LoginService.Login(AppSettings.Setting.ApiServerAddress, UserName, Password);
                }
                else
                {
                    string pemFile = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, AppSettings.Setting.PemFile);
                    result = LoginService.LoginRSA(AppSettings.Setting.ApiServerAddress, pemFile, UserName, Password);
                }

                if (result.success)
                {
                    AppSettings.Setting.Update();

                    //初始化消息管理器
                    if (!MessageManager.Init())
                    {
                        result.success = false;
                        result.message = "MessageManager Init Failed";
                        return result;
                    }

                    //初始化设备管理器
                    if (!DeviceManager.Init())
                    {
                        result.success = false;
                        result.message = "DeviceManager Init Failed";
                        return result;
                    }

                    //初始化下载服务上下文
                    result = DownloadContext.Init(RunAsService);
                    if (!result.success)
                    {
                        return result;
                    }

                    if (DeviceManager.BurnEnable)
                    {
                        //初始化刻录服务上下文
                        result = BurnContext.Init(RunAsService);
                        if (!result.success)
                        {
                            return result;
                        }
                    }
                }
                else
                {
                    Logger.Error("用户名或密码错误");
                }
            }
            else
            {
                result = new HResult() { success = false, message = "未找到配置信息" };
            }

            return result;
        }

        public void Start()
        {
            try
            {
                MessageManager.Start();

                HeartbeatManager.Start();

                DownloadContext.OpenPSDClient();

                if (DeviceManager.BurnEnable)
                {
                    BurnContext.OpenBurnClient();
                }

                var msg = new OpenClientMessage();
                msg.Device = this.Device;

                MessageManager.SendToServer(msg);

                Logger.Info("PSD设备已启动");
            }
            catch (Exception ex)
            { }
        }

        public void Stop()
        {
            HeartbeatManager.Stop();

            DownloadContext.ClosePSDClient();

            if (DeviceManager.BurnEnable)
            {
                BurnContext.CloseBurnClient();
            }

            var msg = new CloseClientMessage();
            msg.DeviceId = Device.id;
            MessageManager.SendToServer(msg);

            MessageManager.Stop();

            Logger.Info("PSD设备已停止");
        }

        public void Dispose(bool exit = true)
        {
            DownloadContext.Dispose(exit);

            BurnContext.Dispose(exit);
        }

        #region Processor Function




        /// <summary>
        /// 重置下载服务
        /// </summary>
        public void RestartService()
        {
            Logger.Info("PSDClient服务即将重启");
            this.Stop();
            this.Dispose();
            var result = this.Init(this.Password, this.LogType, this.RunAsService);

            if (result.success)
            {
                this.Start();
            }
        }

        public void ShutdownDevice()
        {
            Logger.Info("设备即将关闭");
            Stop();
            this.Dispose();
            //WinSystemAPI.ExitWindowsEx(ExitWindows.EWX_SHUTDOWN, 0);
            Process.Start("shutdown.exe", "-s -t 0");
        }

        public void RebootDevice()
        {
            Logger.Info("设备即将重新启动");
            //Stop();
            DownloadContext.ClosePSDClient();

            if (DeviceManager.BurnEnable)
            {
                BurnContext.CloseBurnClient();
            }
            this.Dispose();
            //WinSystemAPI.ExitWindowsEx(ExitWindows.EWX_REBOOT | ExitWindows.EWX_FORCE, 0);
            Process.Start("shutdown.exe", "-r -t 0");
        }

        public void KillService()
        {
            Logger.Info("强制结束服务进程");
            //Stop();
            DownloadContext.ClosePSDClient();

            if (DeviceManager.BurnEnable)
            {
                BurnContext.CloseBurnClient();
            }
            this.Dispose();

            var p1 = Process.GetProcessesByName("PSDClientListener");
            for (int i = p1.Length - 1; i >= 0; i--)
            {
                p1[i].Kill();
            }

            var p2 = Process.GetProcessesByName("PSDClientService");
            for (int i = p2.Length - 1; i >= 0; i--)
            {
                p2[i].Kill();
            }
        }
        #endregion
    }
}
